<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElPagination, ElInput, ElButton, ElDialog, ElForm, ElFormItem } from 'element-plus'
import apiClient from '@/utils/apiClient'

// 角色数据列表
const roleData = ref([])
// 总记录数
const total = ref(0)
// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
// 加载状态
const loading = ref(false)
// 对话框状态
const dialogVisible = ref(false)
const isEditing = ref(false)
// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleLabel: ''
})
// 表单数据
const formData = reactive({
  id: '',
  name: '',
  label: '',
  remark: ''
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取角色列表（支持分页和搜索）
const fetchRoleList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件
    if (searchForm.roleName) {
      params.name = searchForm.roleName
    }
    
    if (searchForm.roleLabel) {
      params.label = searchForm.roleLabel
    }
    
    // 调用角色列表查询接口
    const response = await apiClient.get('/roles', { params })
    
    if (response.data && response.data.code === 1) {
      // 处理返回的数据
      roleData.value = response.data.data.rows.map((item, index) => ({
        ...item,
        displayId: (currentPage.value - 1) * pageSize.value + index + 1,
        lastModifiedTime: formatDateTime(item.updateTime || item.createTime)
      }))
      
      // 更新总数
      total.value = response.data.data.total
    } else {
      ElMessage.error('获取角色列表失败: ' + (response.data?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取角色列表错误:', error)
    
    if (error.response && error.response.status === 401) {
      ElMessage.error('未授权访问，请重新登录')
    } else {
      ElMessage.error('获取角色列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 分页变化处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1 // 重置到第一页
  fetchRoleList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchRoleList()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  fetchRoleList()
}

// 清空搜索
const handleClear = () => {
  searchForm.roleName = ''
  searchForm.roleLabel = ''
  currentPage.value = 1
  fetchRoleList()
}

// 打开添加角色对话框
const handleAddRole = () => {
  isEditing.value = false
  formData.id = ''
  formData.name = ''
  formData.label = ''
  formData.remark = ''
  dialogVisible.value = true
}

// 打开编辑角色对话框
const handleEditRole = async (id) => {
  try {
    // 根据ID查询角色详情
    const response = await apiClient.get(`/roles/${id}`)
    
    if (response.data && response.data.code === 1) {
      const roleInfo = response.data.data
      isEditing.value = true
      formData.id = roleInfo.id
      formData.name = roleInfo.name
      formData.label = roleInfo.label
      formData.remark = roleInfo.remark
      dialogVisible.value = true
    } else {
      ElMessage.error('获取角色详情失败: ' + (response.data?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取角色详情错误:', error)
    ElMessage.error('获取角色详情失败，请稍后重试')
  }
}

// 保存角色
const handleSaveRole = async () => {
  // 表单验证
  if (!formData.name.trim()) {
    ElMessage.warning('请输入角色名称')
    return
  }
  
  if (!formData.label.trim()) {
    ElMessage.warning('请输入角色标识')
    return
  }
  
  try {
    if (isEditing.value) {
      // 修改角色
      const response = await apiClient.put('/roles', formData)
      
      if (response.data && response.data.code === 1) {
        ElMessage.success('修改角色成功')
        dialogVisible.value = false
        fetchRoleList() // 重新加载数据
      } else {
        ElMessage.error('修改角色失败: ' + (response.data?.msg || '未知错误'))
      }
    } else {
      // 添加角色
      const response = await apiClient.post('/roles', formData)
      
      if (response.data && response.data.code === 1) {
        ElMessage.success('添加角色成功')
        dialogVisible.value = false
        fetchRoleList() // 重新加载数据
      } else {
        ElMessage.error('添加角色失败: ' + (response.data?.msg || '未知错误'))
      }
    }
  } catch (error) {
    console.error('保存角色错误:', error)
    
    if (error.response && error.response.status === 401) {
      ElMessage.error('未授权访问，请重新登录')
    } else {
      ElMessage.error('保存角色失败，请稍后重试')
    }
  }
}

// 删除角色
const handleDeleteRole = (id) => {
  ElMessageBox.confirm('确定要删除这个角色吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用删除接口
      const response = await apiClient.delete(`/roles/${id}`)
      
      if (response.data && response.data.code === 1) {
        ElMessage.success('删除成功')
        fetchRoleList() // 重新加载数据
      } else {
        ElMessage.error('删除失败: ' + (response.data?.msg || '未知错误'))
      }
    } catch (error) {
      console.error('删除角色错误:', error)
      
      if (error.response && error.response.status === 401) {
        ElMessage.error('未授权访问，请重新登录')
      } else {
        ElMessage.error('删除角色失败，请稍后重试')
      }
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 初始化时加载数据
onMounted(() => {
  fetchRoleList()
})
</script>

<template>
  <div class="role-management">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchForm.roleName"
        placeholder="请输入角色名称"
        style="width: 200px; margin-right: 10px"
      />
      <el-input
        v-model="searchForm.roleLabel"
        placeholder="请输入角色标识"
        style="width: 200px; margin-right: 10px"
      />
      <div style="float: right">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleClear">清空</el-button>
      </div>
      <el-button type="success" @click="handleAddRole" style="float: left; margin-right: 10px">添加角色</el-button>
    </div>
    
    <!-- 角色列表 -->
    <el-table 
      v-loading="loading" 
      :data="roleData" 
      style="width: 100%"
    >
      <el-table-column prop="displayId" label="序号" width="80" />
      <el-table-column prop="name" label="角色名称" width="180" />
      <el-table-column prop="label" label="角色标识" width="180" />
      <el-table-column prop="remark" label="角色备注" />
      <el-table-column prop="lastModifiedTime" label="最后修改时间" width="200" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEditRole(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="handleDeleteRole(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      :title="isEditing ? '编辑角色' : '添加角色'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识">
          <el-input v-model="formData.label" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="角色备注">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入角色备注" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.role-management {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-table .el-table__header-wrapper th {
  background-color: #409eff !important;
  color: white;
}
</style>
